# coding=utf-8
# 全世界最帅的帅哥
from minio.error import S3Error
from flask import current_app
from ysgg1_club_oss.entity.file_info import FileInfo
from ysgg1_club_oss.minio_client import client
from ysgg1_club_oss.utils.minio_msg import MinioMsg


class MinioUtils:
    @classmethod
    def create_bucket(cls, bucket_name):
        """
        创建桶
        :param bucket_name:
        :return:
        """
        try:
            found = client.bucket_exists(bucket_name)
            if not found:
                client.make_bucket(bucket_name)
                return MinioMsg.create_bucket_success()
            return MinioMsg.create_bucket_existed()

        except S3Error as e:
            current_app.logger.error(e)
            return MinioMsg.create_bucket_fail()

    @classmethod
    def upload_file(cls, bucket_name, file_name, data, length, content_type):
        """
        上传文件
        :param bucket_name:
        :param file_name:
        :param data:
        :param length:
        :param content_type:
        :return:
        """
        try:
            client.put_object(bucket_name, file_name, data, length, content_type)
            # 生成公开 URL
            public_url = f"http://121.40.187.211:9000/{bucket_name}/{file_name}"
            return public_url
        except S3Error as e:
            current_app.logger.error(e)
            return MinioMsg.upload_object_fail()

    @classmethod
    def get_all_bucket(cls):
        """
        得到所有桶
        :return:
        """
        return list(map(lambda bucket: bucket.name, client.list_buckets()))

    @classmethod
    def get_all_file(cls, bucket_name):
        """
        列出当前桶所有内容
        :param bucket_name:
        :return:
        """
        results = client.list_objects(bucket_name)
        file_info_list = []
        for result in results.item:
            file_info = FileInfo()
            file_info.file_name = result.file_name
            file_info_list.append(file_info)

        return file_info_list

    @classmethod
    def download_file(cls, bucket_name, object_name):
        """
        下载文件
        :param object_name:
        :param bucket_name:
        :return:
        """
        return client.get_object(bucket_name, object_name)

    @classmethod
    def remove_bucket(cls, bucket_name):
        """
        删除桶
        :param bucket_name:
        :return:
        """
        client.remove_bucket(bucket_name)

    @classmethod
    def delete_object(cls, bucket_name, object_name):
        """
        删除文件
        :param bucket_name:
        :param object_name:
        :return:
        """
        client.remove_object(bucket_name, object_name)
